<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="举报人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="手机号 / 邮箱，方便回访"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="举报类型" prop="createdAt">
        <el-select v-model="queryParams.type" placeholder="请选择举报类型">
          <el-option label="违规内容" value="1" />
          <el-option label="违规用户" value="2" />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:report:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:report:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:report:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:report:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="举报人ID" align="center" prop="userName" />
      <el-table-column label="举报人" align="center" prop="displayName" />
      <el-table-column label="手机号/邮箱" align="center" prop="contact" />
      <el-table-column label="举报类型" align="center" prop="reportTypeId" />
      <el-table-column label="具体描述" align="center" prop="content" />
      <el-table-column label="举报图片" align="center" prop="url" width="80">
        <template slot-scope="scope">
          <img 
            v-if="scope.row.url" 
            :src="getImageUrl(scope.row.url)" 
            style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover; cursor: pointer;"
            @error="handleImageError"
            @click="previewImage(scope.row.url)"
          />
          <el-avatar v-else :size="40" icon="el-icon-user-solid"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ formatStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
      </el-table-column>
      <el-table-column label="被举报对象" align="center" prop="targetType" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:report:edit']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改举报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="举报类型" prop="reportTypeId" v-if="title !== '审核举报' && title !== '查看审核'">
          <el-select v-model="form.reportTypeId" placeholder="请选择举报类型" style="width: 100%">
            <el-option
              v-for="item in reportTypeOptions"
              :key="item.id"
              :label="item.typeName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体描述" prop="content" v-if="title !== '审核举报' && title !== '查看审核'">
          <el-input v-model="form.content" type="textarea" placeholder="请输入具体的举报文字描述" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact" v-if="title !== '审核举报' && title !== '查看审核'">
          <el-input v-model="form.contact" placeholder="请输入手机号/邮箱" />
        </el-form-item>
        <el-form-item label="审核意见" prop="auditComment" v-if="title === '审核举报' || title === '查看审核'">
          <el-input 
            v-model="form.auditComment" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核意见" 
            :readonly="title === '查看审核'"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title !== '查看审核'">确 定</el-button>
        <el-button @click="cancel">{{ title === '查看审核' ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>
    <!-- 图片预览弹窗 -->
    <el-dialog 
      title="图片预览" 
      :visible.sync="imagePreviewVisible" 
      width="60%" 
      center
      @close="closeImagePreview"
    >
      <div style="text-align: center;">
        <img 
          :src="previewImageUrl" 
          style="max-width: 100%; max-height: 70vh; object-fit: contain;"
          @error="handleImageError"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeImagePreview">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport, auditReport } from "@/api/zl/report"
import { listType } from "@/api/zl/reporttype"

export default {
  name: "Report",
  data() {
    return {
              // 图片预览
      imagePreviewVisible: false,
      previewImageUrl: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        reportTypeId: null,
        content: null,
        contact: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        targetType: null,
        userName: null,
        displayName: null,
        url: null
      },
      // 举报类型选项
      reportTypeOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reportTypeId: [
          { required: true, message: "举报类型不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "具体描述不能为空", trigger: "blur" }
        ],
        auditComment: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getReportTypeList()
  },
  methods: {
      /** 处理图片加载错误 */
    handleImageError(event) {
      // 设置默认头像
      event.target.src = require('@/assets/images/profile.jpg')
      // 或者可以隐藏图片：event.target.style.display = 'none'
    },
        /** 获取图片完整URL */
    getImageUrl(url) {
      if (!url) return ''
      // 清理URL中的空格和反引号
      url = url.trim().replace(/`/g, '');

      // 如果是OSS的完整URL，通过后端下载接口访问
      if (url.startsWith('https://') && url.includes('aliyuncs.com')) {
        return process.env.VUE_APP_BASE_API + '/common/download?fileName=' + encodeURIComponent(url) + '&delete=false'
      }
      
      // 如果已经是完整的HTTP/HTTPS URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }
      
      // 否则拼接BASE_API
      return process.env.VUE_APP_BASE_API + url
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listReport(this.queryParams).then(response => {
        this.reportList = response.rows
        this.total = parseInt(response.total) || 0
        this.loading = false
      })
    },
    /** 获取举报类型列表 */
    getReportTypeList() {
      listType({}).then(response => {
        this.reportTypeOptions = response.rows
      })
    },
    /** 格式化状态显示 */
    formatStatus(status) {
      const statusMap = {
        0: '待审核',
        1: '已审核', 
        2: '已忽略'
      }
      return statusMap[status] || '未知状态'
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        reportTypeId: null,
        content: null,
        contact: null,
        status: null,
        createdAt: null,
        updatedAt: null,
        targetType: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 设置当前登录用户ID作为举报人
      this.form.userId = this.$store.state.user.id
      // 确保举报类型数据已加载
      if (this.reportTypeOptions.length === 0) {
        this.getReportTypeList()
      }
      this.open = true
      this.title = "添加举报"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getReport(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改举报"
      })
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.reset()
      if (row.status === 1) {
        // 已审核状态，只能查看
        getReport(row.id).then(response => {
          this.form = response.data
          this.open = true
          this.title = "查看审核"
        })
      } else {
        // 未审核状态，可以审核
        this.form.id = row.id
        this.open = true
        this.title = "审核举报"
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "审核举报") {
            // 审核举报
            auditReport(this.form).then(response => {
              this.$modal.msgSuccess("审核成功")
              this.open = false
              this.getList()
            })
          } else if (this.form.id != null) {
            // 修改举报
            updateReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // 新增举报
            addReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除举报编号为"' + ids + '"的数据项？').then(function() {
        return delReport(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/report/export', {
        ...this.queryParams
      }, `report_${new Date().getTime()}.xlsx`)
    },
    /** 预览图片 */
    previewImage(url) {
      this.previewImageUrl = this.getImageUrl(url);
      this.imagePreviewVisible = true;
    },
    
    /** 关闭图片预览 */
    closeImagePreview() {
      this.imagePreviewVisible = false;
      // this.previewImageUrl = '';
    }
  }
}
</script>
